package com.pmt.feedplayer.ui

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.pmt.feedplayer.ui.AudioPlayerViewModel
import java.io.File

/**
 * 音频播放器屏幕
 */
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AudioPlayerScreen(audioFile: File, viewModel: AudioPlayerViewModel, onClose: () -> Unit) {
    val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
    val coroutineScope = rememberCoroutineScope()
    
    // 播放状态
    var isPlaying by remember { mutableStateOf(viewModel.isPlaying.value ?: false) }
    var currentPosition by remember { mutableFloatStateOf(0f) }
    var duration by remember { mutableFloatStateOf(1f) }
    var isSeeking by remember { mutableStateOf(false) }
    
    // 监听播放状态变化
    DisposableEffect(key1 = viewModel.isPlaying) {
        val observer = { playing: Boolean ->
            isPlaying = playing
        }
        viewModel.isPlaying.observeForever(observer)
        
        onDispose {
            viewModel.isPlaying.removeObserver(observer)
        }
    }
    
    // 监听播放位置变化
    DisposableEffect(key1 = viewModel.currentPosition) {
        val positionObserver = { position: Long ->
            if (!isSeeking) {
                currentPosition = position.toFloat()
            }
        }
        viewModel.currentPosition.observeForever(positionObserver)
        
        onDispose {
            viewModel.currentPosition.removeObserver(positionObserver)
        }
    }
    
    // 监听音频总时长变化
    DisposableEffect(key1 = viewModel.duration) {
        val durationObserver = { totalDuration: Long ->
            duration = totalDuration.toFloat()
        }
        viewModel.duration.observeForever(durationObserver)
        
        onDispose {
            viewModel.duration.removeObserver(durationObserver)
        }
    }
    
    // 在组件初始化时加载并播放音频
    DisposableEffect(key1 = audioFile) {
        // 加载音频文件
        viewModel.loadAudio(audioFile)
        // 开始播放
        viewModel.playAudio()
        
        // 清理
        onDispose {
            viewModel.pauseAudio()
        }
    }
    
    Column(modifier = Modifier.fillMaxSize()) {
        // 顶部导航栏
        CenterAlignedTopAppBar(
            title = { Text(text = "音频播放") },
            navigationIcon = {
                IconButton(onClick = onClose) {
                    Icon(imageVector = Icons.Default.Close, contentDescription = "关闭")
                }
            },
            scrollBehavior = scrollBehavior
        )
        
        // 主要内容区域
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 专辑封面占位
            Column(
                modifier = Modifier
                    .size(300.dp)
                    .padding(16.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // 简单的音频可视化占位
                repeat(5) { index ->
                    Spacer(modifier = Modifier.height(8.dp))
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        repeat(5) { colIndex ->
                            Spacer(modifier = Modifier.size(8.dp))
                            Box(
                                modifier = Modifier
                                    .size(
                                        width = 16.dp,
                                        height = if (isPlaying) (20 + Math.random() * 60).dp else 20.dp
                                    )
                                    .background(MaterialTheme.colorScheme.primary)
                            )
                        }
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(32.dp))
            
            // 歌曲信息
            Text(
                text = audioFile.nameWithoutExtension,
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Center,
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = formatFileSize(audioFile.length()),
                fontSize = 14.sp,
                color = Color.Gray
            )
            
            Spacer(modifier = Modifier.height(32.dp))
            
            // 进度条
            Column(modifier = Modifier.fillMaxWidth()) {
                Slider(
                    value = currentPosition,
                    onValueChange = { newValue ->
                        isSeeking = true
                        currentPosition = newValue
                    },
                    onValueChangeFinished = {
                        isSeeking = false
                        viewModel.seekTo(currentPosition.toInt())
                    },
                    valueRange = 0f..duration,
                    modifier = Modifier.fillMaxWidth()
                )
                
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(text = formatTime(currentPosition.toInt()))
                    Text(text = formatTime(duration.toInt()))
                }
            }
            
            Spacer(modifier = Modifier.height(32.dp))
            
            // 播放控制按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 快退
                IconButton(
                    onClick = { viewModel.rewind(10000) },
                    modifier = Modifier.size(48.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.PlayArrow,
                        contentDescription = "快退10秒",
                        modifier = Modifier.size(32.dp)
                    )
                }
                
                Spacer(modifier = Modifier.size(24.dp))
                
                // 播放/暂停
                IconButton(
                    onClick = { 
                        viewModel.togglePlayPause()
                    },
                    modifier = Modifier.size(64.dp)
                ) {
                      Icon(
                         imageVector = Icons.Default.PlayArrow,
                          contentDescription = if (isPlaying) "暂停" else "播放",
                          modifier = Modifier.size(48.dp)
                      )
                }
                
                Spacer(modifier = Modifier.size(24.dp))
                
                // 快进
                IconButton(
                    onClick = { viewModel.fastForward(10000) },
                    modifier = Modifier.size(48.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.PlayArrow,
                        contentDescription = "快进10秒",
                        modifier = Modifier.size(32.dp)
                    )
                }
            }
        }
    }
}

/**
 * 格式化时间（毫秒转为 mm:ss）
 */
fun formatTime(milliseconds: Int): String {
    val totalSeconds = milliseconds / 1000
    val minutes = totalSeconds / 60
    val seconds = totalSeconds % 60
    return String.format("%02d:%02d", minutes, seconds)
}

/**
 * 格式化文件大小
 */
fun formatFileSize(bytes: Long): String {
    if (bytes < 1024) return "$bytes B"
    else if (bytes < 1024 * 1024) return "${String.format("%.2f", bytes / 1024.0)} KB"
    else return "${String.format("%.2f", bytes / (1024.0 * 1024))} MB"
}